<template>
  <div>
    商品名称:
    <el-input v-model="query.billName" placeholder="请输入名字" style="width: 200px"></el-input>
    &emsp;&emsp;
    供应商：
    <el-select v-model="query.sid" placeholder="请选择供应商">
      <el-option
        v-for="item in supplierList"
        :key="item.id"
        :label="item.supplierName"
        :value="item.id">
      </el-option>
    </el-select>
    &emsp;&emsp;
    是否付款:
    <el-select v-model="query.status" placeholder="请选择状态">
      <el-option label="未付款" :value="1"></el-option>
      <el-option label="已付款" :value="2"></el-option>
    </el-select> &emsp;&emsp;
    <el-button type="primary" @click="initAll" plain>查询</el-button>
    <el-button type="primary" @click="iniData" plain>重置</el-button>
    <el-button type="primary" @click="add" plain>添加账单</el-button>

    <el-button type="success" @click="countData(1)" plain>饼状图统计</el-button>
    <el-button type="success" @click="countData(2)" plain>柱状图统计</el-button>
    <el-button type="success" @click="countData(3)" plain>折线图统计</el-button>

    <el-dialog title="统计三级图之一" :visible.sync="countDialogFlag" top="5px">
      <!--放echarts相关代码-->
      <div id="main" style="width: 500px;height: 400px"></div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="countDialogFlag = false">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="mode.title" :visible.sync="dialogFormVisible" width="500px">
        <el-form :model="form" :rules="rules" ref="form" label-width="100px" class="demo-form">
        <el-form-item label="账单编码" :label-width="formLabelWidth" prop="billCoding">
          <el-input v-model="form.billCoding" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="商品名称" :label-width="formLabelWidth" prop="billName">
          <el-input v-model="form.billName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="商品单位" :label-width="formLabelWidth" prop="billUnit">
          <el-input v-model="form.billUnit" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="商品数量" :label-width="formLabelWidth" prop="billNum">
          <el-input v-model="form.billNum" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="总金额" :label-width="formLabelWidth" prop="sumMoney">
          <el-input v-model="form.sumMoney" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="供应商" :label-width="formLabelWidth" prop="sid">
          <el-select v-model="form.sid" placeholder="请选择老师">
            <el-option
              v-for="item in supplierList"
              :key="item.id"
              :label="item.supplierName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">未付款</el-radio>
            <el-radio :label="2">已付款</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="sumbit()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="详情" :visible.sync="dialogFormVisible2" width="500px">
      <b>账单编码:</b><b style="color: cornflowerblue">{{ form.billCoding }}</b><br>
      <b>商品名称:</b><b style="color: cornflowerblue">{{ form.billName }}</b><br>
      <b>单位:</b><b style="color: cornflowerblue">{{ form.billUnit }}</b><br>
      <b>数量:</b><b style="color: cornflowerblue">{{ form.billNum }}</b><br>
      <b>总金额:</b><b style="color: cornflowerblue">{{ form.sumMoney }}</b><br>
      <b>供应商:</b><b style="color: cornflowerblue">{{ form.sname }}</b><br>
      <b>是否付款:</b><b style="color: cornflowerblue">
      {{ form.status == 1 ? '未付款' : '' }}
      {{ form.status == 2 ? '已付款' : '' }}</b><br>
      <b>创建时间:</b><b style="color: cornflowerblue"> {{ form.addTime |format('yyyy-MM-dd hh:mm:ss') }}</b><br>
      <br>
      <el-button type="primary" @click="dialogFormVisible2=false">返回</el-button>
    </el-dialog>

    <el-table
      :data="tableData"
      style="width: 100%"
      border>
      <el-table-column
        prop="billCoding"
        label="账单编码">
      </el-table-column>
      <el-table-column
        prop="billName"
        label="商品名称"
        width="180">
      </el-table-column>
      <el-table-column
        prop="sname"
        label="供应商">
      </el-table-column>
      <el-table-column
        prop="sumMoney"
        label="总金额">
      </el-table-column>
      <el-table-column
        prop="status"
        label="是否付款">
        <template slot-scope="scope">
          {{ scope.row.status == 1 ? '未付款' : '' }}
          {{ scope.row.status == 2 ? '已付款' : '' }}
        </template>
      </el-table-column>
      <el-table-column
        prop="addTime"
        label="创建时间">
        <template slot-scope="scope">
          {{ scope.row.addTime == null ? '' : scope.row.addTime | format('yyyy-MM-dd hh:mm:ss') }}
        </template>
      </el-table-column>
      <el-table-column
        prop="updateTime"
        label="修改时间">
        <template slot-scope="scope">
          {{ scope.row.updateTime == null ? '' : scope.row.updateTime | format('yyyy-MM-dd hh:mm:ss') }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="info" icon="el-icon-chat-line-square" circle
            @click="Info(scope.row)">
          </el-button>
          <el-button
            type="primary" icon="el-icon-edit"
            @click="handleEdit(scope.row)" circle>
          </el-button>
          <el-button
            @click="handleDelete(scope.row.id)" type="danger" icon="el-icon-close" circle>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination style="text-align: left"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
                   :current-page="query.pageNum"
                   :page-sizes="[3, 4, 6, 400]"
                   :page-size="query.pageSize"
                   layout="total, sizes, prev, pager, next, jumper"
                   :total="total">
    </el-pagination>
  </div>
</template>

<script>
import * as echarts from 'echarts';
export default {
  data() {
    return {
      countDialogFlag: false,//统计弹窗展示和隐藏的变量
      user: {},
      tableData: [],
      total: 0,
      supplierList: [],
      query: {
        pageNum: 1,
        pageSize: 3,
        billName: "",
        status: "",
        sid: "",
      },
      dialogFormVisible: false,
      dialogFormVisible2: false,
      form: {
        id: "",
        billCoding: "",
        billName: "",
        sumMoney: "",
        status: "",
        addTime: "",
        updateTime: "",
        sid: "",
        billNum: "",
        billUnit: "",
      },
      formLabelWidth: '120px',
      mode: {
        title: "",
        url: "",
      },
      rules: {
        billCoding: [
          {required: true, message: '请输入名字', trigger: 'blur'}
        ],
        billName: [
          {required: true, message: '请选择商品名称', trigger: 'blur'}
        ],
        billUnit: [
          {required: true, message: '请选择性别', trigger: 'change'}
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        sid: [
          { required: true, message: '请选择', trigger: 'change' }
        ],

      }
    }
  },
  filters: {
    format(value, arg) {
      function dateFormat(date, format) {
        if (typeof date === "string") {
          var mts = date.match(/(\/Date\((\d+)\)\/)/);
          if (mts && mts.length >= 3) {
            date = parseInt(mts[2]);
          }
        }
        date = new Date(date);
        if (!date || date.toUTCString() == "Invalid Date") {
          return "";
        }
        var map = {
          "M": date.getMonth() + 1, //月份
          "d": date.getDate(), //日
          "h": date.getHours(), //小时
          "m": date.getMinutes(), //分
          "s": date.getSeconds(), //秒
          "q": Math.floor((date.getMonth() + 3) / 3), //季度
          "S": date.getMilliseconds() //毫秒
        };
        format = format.replace(/([yMdhmsqS])+/g, function (all, t) {
          var v = map[t];
          if (v !== undefined) {
            if (all.length > 1) {
              v = '0' + v;
              v = v.substr(v.length - 2);
            }
            return v;
          } else if (t === 'y') {
            return (date.getFullYear() + '').substr(4 - all.length);
          }
          return all;
        });
        return format;
      }

      return dateFormat(value, arg);

    }
  },
  methods: {
    countData(type){
      const config = {
        headers: {"token": localStorage.getItem("token")}
      }
      this.countDialogFlag = true;
      //注意修改统计接口的路径
      this. axios.get("/bill/echarts",config).then(res=>{
        let list = res.data;
        //echarts初始化
        setTimeout(()=>{
          this.initEchartsData(list,type)
        },100)
      })
    },
    initEchartsData(list,type){
      // 基于准备好的dom，初始化echarts实例
      const myChart = echarts.init(document.getElementById('main'));
      myChart.clear()//清空echarts
      //data--[{name:"",value:""}]
      // 指定图表的配置项和数据
      let option = {};
      if(type==1){//饼状图
        option = {
          tooltip: {
            trigger: 'item'
          },
          legend: {
            top: '5%',
            left: 'center'
          },
          series: [
            {
              name: 'Access From',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: 40,
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: list
            }
          ]
        };

        option && myChart.setOption(option);
      }
      else if(type==2){//柱状图
        let xdata = [];
        let ydata = [];
        for (let i = 0; i < list.length; i++) {
          xdata.push(list[i].name);
          ydata.push(list[i].value);
        }
        option = {
          title: {
            text: ''
          },
          tooltip: {},
          legend: {
            data:['数量']
          },
          xAxis: {
            data: xdata
          },
          yAxis: {},
          series: [{
            name: '数量',
            type: 'bar',
            data: ydata
          }]
        };
      }else if(type==3){
        let xdata = [];
        let ydata = [];
        // status
        for (let i = 0; i < list.length; i++) {
          xdata.push(list[i].name);
          ydata.push(list[i].value);
        }
        option = {
          title: {
            text: ''
          },
          tooltip: {},
          legend: {
            data:['数量']
          },
          xAxis: {
            data: xdata
          },
          yAxis: {},
          series: [{
            name: '数量',
            type: 'line',
            data: ydata
          }]
        };
      }
      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);
    },

    Info(e) {
      this.form = e;
      this.dialogFormVisible2 = true;
    },
    handleEdit(e) {
      this.form = e;
      this.dialogFormVisible = true;
      this.mode = {
        title: "修改",
        url: '/bill/handEdit'
      }

    },
    add() {
      this.dialogFormVisible = true;
      this.forces();
      this.mode = {
        title: "添加",
        url: '/bill/add',
      }
    },
    sumbit() {
      const config = {
        headers: {"token": localStorage.getItem("token")}
      }
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.axios.post(this.mode.url, this.form, config).then((res) => {
            if (res.data.code == 200) {
              this.$message.success(res.data.message);
              this.initAll();
              this.forMent();
            } else {
              this.$message.error(res.data.message);
            }
          })
        }
      })
    },
    forces() {
      this.form = {
        id: "",
        billCoding: "",
        billName: "",
        sumMoney: "",
        status: "",
        addTime: "",
        updateTime: "",
        sid: "",
        billNum: "",
        billUnit: "",
      };
    }
    ,
    forMent() {
      this.dialogFormVisible = false;
      this.form = {
        id: "",
        billCoding: "",
        billName: "",
        sumMoney: "",
        status: "",
        addTime: "",
        updateTime: "",
        sid: "",
        billNum: "",
        billUnit: "",
      };
    }
    ,
    iniData() {
      this.query = {
        billName: "",
        status: "",
        sid: "",
      };
      this.query.pageNum = 1;
      this.query.pageSize = 3;
      this.initAll();
    }
    ,
    handleDelete(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const config = {
          headers: {"token": localStorage.getItem("token")}
        }
        this.axios.post(`/bill/handDelete?id=` + id, null, config).then((res) => {
          if (res.data.code == 200) {
            this.$message.success(res.data.message);
            this.initAll();
          } else {
            this.$message.error(res.data.message);
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });


    }
    ,
    initAll() {
      const config = {
        headers: {"token": localStorage.getItem("token")}
      }
      this.axios.post(`/bill/billFindPage?pageNum=` + this.query.pageNum + "&pageSize=" + this.query.pageSize, this.query, config).then((res) => {
        this.tableData = res.data.records;
        this.total = res.data.total;
      });
      if (this.tableData.length == 0 && this.query.pageNum > 1) {
        this.query.pageNum--;
        this.initAll();
      }
    }
    ,
    supplier() {
      const config = {
        headers: {"token": localStorage.getItem("token")}
      }
      this.axios.get(`/bill/supplierList`, config).then((res) => {
        console.log(res.data);
        this.supplierList = res.data;
      })
    }
    ,
    handleSizeChange(val) {
      this.query.pageSize = val;
      this.initAll();
    }
    ,
    handleCurrentChange(val) {
      this.query.pageNum = val;
      this.initAll();
    }
  },
  created() {
    this.user = JSON.parse(localStorage.getItem("user"))
    this.initAll();
    this.supplier();

  }
}
</script>

<style>

</style>




